package cn.jimmie.lib.qlog;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * Func :
 *
 * <p> Create Time:  2019-12-18 12:59 </p>
 * <p> @author Jimmie.Qian  </p>
 */
final class RecyclerLogExecutor implements Runnable {
    private final BlockingDeque<RecyclerLog> queue = new LinkedBlockingDeque<>();
    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    private OnMessageListener listener;
    private volatile boolean quit = false;

    RecyclerLogExecutor(OnMessageListener listener) {
        this.listener = listener;
    }

    void add(QLogLevel level, String source) {
        RecyclerLog rl = RecyclerLog.obtain();
        rl.queue = queue;
        rl.level = level;
        rl.message = source;
        executor.execute(rl.callback);
    }

    void release() {
        quit = true;
        queue.clear();
        executor.shutdownNow();
        listener = null;
    }

    @Override
    public void run() {
        listener.onPreQueueStart();

        while (!quit) {
            try {
                RecyclerLog log = queue.take();
                listener.onLogReach(log.level, log.message);
                log.recycle();
            } catch (Throwable ignored) {
                break;
            }
        }
    }

    public interface OnMessageListener {
        void onPreQueueStart();

        void onLogReach(QLogLevel level, String message);
    }
}
